import { createSlice } from "@reduxjs/toolkit";
import { useSelector } from "react-redux";
import { getHospitalSet, getHospitalSetLockId, postHospitalSet, putHospitalSet } from "@/api/hosp";
import { changeLoading, changePageInfo } from "./common";


const hospSlice = createSlice({
    name: "hosp",
    initialState: {
        hospSetList: []
    },
    reducers: {
        upHospSetList(state, { payload }) {

            state.hospSetList = payload;
        },
        changeStateById(state,{payload}){
            const info:any = state.hospSetList.find((v:any)=>v.id === payload);
            info.status = info.status===0?1:0;
        }
    }
})
const { upHospSetList,changeStateById } = hospSlice.actions;

//获取状态列表
export const getHospitalSetAsync = (page: number, limit: number) => {
    return async (dispatch: any) => {
        const result = await getHospitalSet(page, limit);
        // 更新新闻设置列表状态
        dispatch(upHospSetList(result.data.records))
        dispatch(changePageInfo({
            current:result.data.current,
            total:result.data.total,
            pageSize:result.data.size
        }))
        dispatch(changeLoading(false));
    }
}


 // 完成锁定1： 优点：减少ajax请求
  // export const getHospitalSetLockIdAsync = function(id:number,status:number){
  //     return async (dispatch:any)=>{
  //         await getHospitalSetLockId(id,status);
  //         dispatch(changeStateById(id));
  //     }
  // }


// 完成锁定2:更新服务端的锁定状态，然后重新获取当前页的信息，进行渲染
// 优点：可以将最后操作以后的最新数据进行呈现
export const getHospitalSetLockIdAsync = (id: number, status: number) => {
    return async (dispatch: any,getState:any) => {
        await getHospitalSetLockId(id, status);
        const {current,pageSize} = getState().common.pageInfo
        dispatch(getHospitalSetAsync(current,pageSize));
    }
}

/*   // 添加医院设置
export const postHospitalSetAsync = (body: any) => {
    return async (dispatch: any,getState:any) => {
        await postHospitalSet(body);
        dispatch(getHospitalSetAsync(1,getState().common.pageInfo.pageSize))
    }
} */


// 添加或修改医院设置
export const postHospitalSetAsync = (body:any)=>{
    return async (dispatch:any,getState:any)=>{
        if(body.id){
            // 修改
            await putHospitalSet(body);
        }else{
            // 添加
            await postHospitalSet(body);
        }
        const {current,pageSize} = getState().common.pageInfo;
        dispatch(getHospitalSetAsync(current,pageSize));
    }
}
// 导出状态
export const useSelectorHosp = () => useSelector((state: any) => state.hosp);
export default hospSlice.reducer;